/*
 * Member.cpp
 *
 *  Created on: 2014. 7. 17.
 *      Author: mega
 */

#include "../Member.h"
#include "../Enum.h"
#include "../Function.h"
#include "../NResource/Static.h"
#include <Database/Static.h>
#include <Logger/Static.h>

namespace GuildServer {

Member::Member() : m_UserSeq(0), m_bFlushDB(false)
{
	m_MemberInfo.Clear();
}

Member::~Member()
{

}

void
Member::Initialize(uint32_t userSeq)
{
	m_UserSeq = userSeq;
	m_bFlushDB = false;
	m_MemberInfo.Clear();
}

void
Member::Finalize()
{

}

void
Member::Open(MemberInfo & info)
{
	m_MemberInfo = info;
}

void
Member::FlushMemberPoint()
{
	if (false == m_bFlushDB)
		return;

	Database::ResultSet res = Database::Execute(static_cast<int>(DatabaseType::GUILD_MASTER),
				"call sp_update_guild_member_point(",
					m_UserSeq, ",",
					m_MemberInfo._guildSeq, ",",
					m_MemberInfo._contributeScore, ",",
					m_MemberInfo._dailyScore, ",",
					m_MemberInfo._dailyInitTime, ")"
			);

	if (0 != res.GetSQLError())
	{
		LOG(ERR, __FUNCTION__, " Fail call sp_update_guild_member_point");
		return;
	}

	auto iter = res.begin();

	int nRet = iter->getInt(1);

	if (0 != nRet)
	{
		LOG(ERR, __FUNCTION__, " Member point update exception. nRet : ", nRet);
		return;
	}

	m_bFlushDB = false;
}

void
Member::FlushLoginTime()
{
	// 로그인 시간 DB 갱신
	Database::ResultSet res = Database::Execute(static_cast<int>(DatabaseType::GUILD_MASTER),
				"call sp_update_guild_member_login_time(",
					m_MemberInfo._guildSeq, ",",
					m_UserSeq, ",",
					m_MemberInfo._loginTime, ")"
			);

	if (0 != res.GetSQLError())
	{
		LOG(ERR, __FUNCTION__, " Fail call sp_update_guild_member_login_time.");
		return;
	}

	auto iter = res.begin();

	int nRet = iter->getInt(1);

	if (0 != nRet)
	{
		LOG(ERR, __FUNCTION__, " Member login time update exception. nRet : ", nRet);
		return;
	}
}

void
Member::ChangeMemberScore(int score, int dailyMaxScore)
{
	// 누적 점수 반영
	m_MemberInfo._contributeScore += score;
	if (0 >= m_MemberInfo._contributeScore)
		m_MemberInfo._contributeScore = 0;


	// 일일 획득 점수 초기화
	time_t initTime = GetMemberScoreDailyInitTime();

	if (initTime >= m_MemberInfo._dailyInitTime)
	{
		m_MemberInfo._dailyScore = 0;
		m_MemberInfo._dailyInitTime = time(NULL);
	}

	// 일일 획득 점수 반영
	m_MemberInfo._dailyScore += score;
	if (0 >= m_MemberInfo._dailyScore)
		m_MemberInfo._dailyScore = 0;

	if (dailyMaxScore <= m_MemberInfo._dailyScore)
		m_MemberInfo._dailyScore = dailyMaxScore;

}

} /*GuildServer*/


